package org.mengyun.tcctransaction.sample.service;

import java.util.Optional;

import org.mengyun.tcctransaction.api.Compensable;
import org.mengyun.tcctransaction.api.TransactionContext;
import org.mengyun.tcctransaction.sample.domain.dto.OrderDto;
import org.mengyun.tcctransaction.sample.domain.entity.Product;
import org.mengyun.tcctransaction.sample.domain.repository.ProductRepository;
import org.mengyun.tcctransaction.sample.domain.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by changming.xie on 4/1/16.
 */
@Service("productService")
public class ProductService implements IProductService {

	@Autowired
	ProductRepository productRepository;

	@Override
	@Compensable(confirmMethod = "confirmReduceStock", cancelMethod = "cancelReduceStock", asyncConfirm = true)
	@Transactional
	public String reduceStock(TransactionContext tc, OrderDto od) {
		System.out.println("==========================reduceStock:" + od);

		Optional<Product> op = productRepository.findById(od.getProductId());
		if (op.isPresent()) {
			Product p = op.get();
			p.setTccNum(p.getTccNum() + od.getNum());
			p.setNum(p.getNum() - p.getTccNum());
			productRepository.save(p);

			return "ok";
		}
		throw new RuntimeException("can not find Product:" + od);

	}

	public void confirmReduceStock(TransactionContext tc, OrderDto od) {
		System.out.println("*****************************=====confirmReduceStock:" + od);

		Optional<Product> op = productRepository.findById(od.getProductId());
		if (op.isPresent()) {
			Product p = op.get();
			p.setTccNum(p.getTccNum() - od.getNum());
			// p.setNum(p.getNum()+od.getNum());
			productRepository.save(p);
		}

	}

	public void cancelReduceStock(TransactionContext tc, OrderDto od) {
		System.out.println("xxxxxxxxxxxxxxxxxxxxxxxx======cancelReduceStock:" + od);
		Optional<Product> op = productRepository.findById(od.getProductId());
		if (op.isPresent()) {
			Product p = op.get();
			p.setTccNum(p.getTccNum() - od.getNum());
			p.setNum(p.getNum() + od.getNum());
			productRepository.save(p);
		}
	}

}
